package com.Lixiaoqian.PartyHistoryMuseum.ui;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.Lixiaoqian.PartyHistoryMuseum.R;
import com.Lixiaoqian.PartyHistoryMuseum.bean.BannerBean;
import com.Lixiaoqian.PartyHistoryMuseum.net.ApiConstant;
import com.Lixiaoqian.PartyHistoryMuseum.utils.Constant;
import com.Lixiaoqian.PartyHistoryMuseum.utils.ZipExtractorTask;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 资源下载页面
 */
public class LoadActivity extends AppCompatActivity implements View.OnClickListener {
    public static int LAUNCH_ARACTIIVTY=0;
    public static int LAUNCH_VIDEOACTIIVTY=1;
    public static String ACTION_UPDATE_FINISH="finish";
    public static String ACTION_UPDATE="update";
    private static  String INTENT_RES="res";
    public static  String INTENT_JUMP_MODE="jumpMode";
    public  static int position;
    @BindView(R.id.tv_loading_info)
    TextView tvLoadingInfo;
    @BindView(R.id.tv_loading_num)
    TextView tvLoadingNum;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.im_loading_cancle)
    TextView imLoadingCancle;
    private AsyncTask<String, Integer, String> downTask;
    private ZipExtractorTask zipExtractorTask;
    private BannerBean bannerBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE); //去除这个Activity的标题栏
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_load);
        ButterKnife.bind(this);
        bannerBean = (BannerBean) getIntent().getSerializableExtra(INTENT_RES);
        initEvent();
        downTask = new DownResTask().execute(ApiConstant.IMAGE_BASE_URL+bannerBean.getContent_file());
    }

    private void initEvent() {
        imLoadingCancle.setOnClickListener(this);
    }


    public static void launch(Context fromActivity, BannerBean bannerBean) {
        Intent intent = new Intent(fromActivity, LoadActivity.class);
        intent.putExtra(INTENT_RES,bannerBean);
        fromActivity.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.im_loading_cancle:
                finish();
                downTask.cancel(true);
                if (zipExtractorTask!=null)
                zipExtractorTask.cancel(true);
                break;
        }
    }

    /**
     * 下载zip文件内部类
     */
    private class DownResTask extends AsyncTask<String, Integer, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
        }

        //doInBackground方法内部执行后台任务,不可在此方法内修改UI
        @Override
        protected String doInBackground(String... params) {
            try {
                downFile(params[0]);
            } catch (Exception e) {
            }
            return null;
        }

        /*
         * 下载zip文件逻辑
         *
         * @param param
         * @throws IOException
         * */

        private void downFile(String param) throws IOException {
            //连接地址
            URL url = new URL(param);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            int lenghtOfFile = c.getContentLength();//计算长度
            c.connect();
            FileOutputStream f = new FileOutputStream(new File(Constant.ZIP_PATH, Constant.ZIP_FILE_NAME + ".zip"));
            InputStream in = c.getInputStream();
            //下载的代码
            byte[] buffer = new byte[1024];
            int len1 = 0;
            long total = 0;

            while ((len1 = in.read(buffer)) > 0) {
                total += len1; //total = total + len1
                publishProgress((int) ((total * 100) / lenghtOfFile));
                f.write(buffer, 0, len1);
            }
            f.close();
        }

        //onProgressUpdate方法用于更新进度信息
        @Override
        protected void onProgressUpdate(Integer... progresses) {
            progressBar.setProgress(progresses[0]);
            tvLoadingNum.setText(progresses[0] + "%");
        }

        //onPostExecute方法用于在执行完后台任务后更新UI,显示结果
        @Override
        protected void onPostExecute(String result) {
            tvLoadingNum.setText(result);
            tvLoadingInfo.setText("正在解压资源文件");
            zipExtractorTask = new ZipExtractorTask(Constant.ZIP_PATH+"/"+Constant.ZIP_FILE_NAME + ".zip",
                    Constant.ZIP_PATH, LoadActivity.this,
                    tvLoadingInfo,bannerBean);
            zipExtractorTask.execute();
        }

        //onCancelled方法用于在取消执行中的任务时更改UI
        @Override
        protected void onCancelled() {
        }
    }



}
